package com.nexgo.payment.action.confirmtransdetail;

import android.support.annotation.NonNull;

import com.nexgo.payment.App;
import com.nexgo.payment.R;
import com.nexgo.payment.aop.annotation.RunOnMainThread;
import com.nexgo.payment.constrant.SysConstant;
import com.nexgo.payment.databases.DataSource;
import com.nexgo.payment.databases.TransRecord;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * 显示交易详情操作
 *
 * @author 谭忠扬-YuriTam
 * @time 2017年8月25日
 */
public class ConfirmTransDetailPresenter implements ConfirmTransDetailContract.Presenter {
    private Logger mLog = LoggerFactory.getLogger(ConfirmTransDetailPresenter.class.getSimpleName());

    private ConfirmTransDetailContract.View mView;
    private DataSource mRepository;
    private String mTraceNum;
    private TransRecord mTransRecord;
    private boolean isFirstTimes = true;

    public ConfirmTransDetailPresenter(@NonNull ConfirmTransDetailContract.View view, @NonNull DataSource repository, @NonNull String traceNum) {
        mView = checkNotNull(view);
        mRepository = checkNotNull(repository);
        mTraceNum = checkNotNull(traceNum);
        view.setPresenter(this);
    }

    @Override
    public void start() {
        if (isFirstTimes) {
            queryTransDetail(mTraceNum);
            isFirstTimes = false;
        }
    }

    @Override
    public void pause() {

    }

    @Override
    public void destroy() {

    }

    private void queryTransDetail(String traceNum) {
        //根据入参的长度判断是否凭证号还是凭证码
        if (traceNum.length() == 6) {
            mTransRecord = mRepository.queryTransRecord(traceNum);
        } else {
            mTransRecord = mRepository.queryScanTransRecord(traceNum);
        }
        if (mTransRecord == null) {
            postMainThread(() -> mView.showErrMsg(App.sContext.getString(R.string.trace_num_not_exsit)));
            postMainThread(() -> mView.showEmptyTransRecord());
            return;
        }
        postMainThread(() -> mView.showTransDetail(mTransRecord));
    }

    @Override
    public void confirmDetail() {
        //判断是否当天交易，只可撤销当天交易
//        wzp delete
/*        String dateStr = new SimpleDateFormat("MMdd", SysConstant.LOCALE).format(new Date());
        mLog.debug("current Date = {}, trans date = {}", dateStr, mTransRecord.getDate());
        if (!mTransRecord.getDate().equals(dateStr)){
            postMainThread(() -> mView.showErrMsg(App.sContext.getString(R.string.can_not_void_and_pls_refund)));
            return;
        }*/
        postMainThread(() -> mView.showConfirm(mTransRecord));
    }

    @RunOnMainThread
    private void postMainThread(Runnable runnable) {
        if (mView.isActive()) {
            runnable.run();
        }
    }
}
